<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/5
 * Time: 18:56
 */

namespace App\HttpController\Home;


use App\Enums\SysKeyEnums;
use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

class Demo extends Base
{

    public function oncoming()
    {
        $data = [];
        $option = [
            'path'      =>UrlEnums::LOL_RECENTLY_MATCHS_PATH,
            'api_time'  => $this->getMillisecond()
        ];
        $params = [
            'query'     => [
                'offset' => 0,
                'limit'  => 10,
                'version'=> 2
            ],
            'header'    => Auth::getInstance($option)->header()
        ];
        $res = $this->handleCurl('GET',UrlEnums::FJURL.UrlEnums::LOL_RECENTLY_MATCHS_PATH,$params);
        if( $res['code'] == 200 ){
            $data = $res['data'];
        }
        if( !empty($data) ){
            foreach ( $data as $k=>$v ){
                $data[$k]['start_time'] = $this->getMsecToMescdate($v['start_time']);
            }
        }
        return $this->writeJson(200,$data,'请求成功');
    }

    /**
     * 比赛详情
     * @return bool
     */
    public function matchInfo()
    {
        $match_id = $this->request()->getRequestParam('match_id');
        if(empty($match_id)) return $this->writeJson(1001,[],'缺少match_id');;

        $data = [];
        $option = [
            'path'      =>UrlEnums::LOL_BASICINOF_MATCH_PATH,
            'api_time'  => $this->getMillisecond()
        ];
        $params = [
            'query'     => [
                'version'   => 2,
                'match_id'  => $match_id
            ],
            'header'    => Auth::getInstance($option)->header()
        ];
        $res = $this->handleCurl('GET',UrlEnums::FJURL.UrlEnums::LOL_RECENTLY_MATCHS_PATH,$params);
        if( $res['code'] == 200 ){
            $data = $res['data'];
        }
        if( !empty($data) ){
            $data['start_time'] = $this->getMsecToMescdate($data['start_time']);
        }
        return $this->writeJson(200,$data,'请求成功');
    }

    /**
     * 现场比分
     * @return bool
     */
    public function liveScore()
    {
        $data = [];
        $option = [
            'path'      =>UrlEnums::LOL_LIVE_MATCH_PATH,
            'api_time'  => $this->getMillisecond()
        ];
        $params = [
            'query'     => [
                'version'=> 2
            ],
            'header'    => Auth::getInstance($option)->header()
        ];
        print_r($params);
        $res = $this->handleCurl('GET',UrlEnums::FJURL.UrlEnums::LOL_LIVE_MATCH_PATH,$params);
        if( $res['code'] == 200 ){
            $data = $res['data'];
        }
        return $this->writeJson(200,$data,'请求成功');
    }

    public function teamInfo()
    {
        $data = [];
        $option = [
            'path'      =>UrlEnums::LOL_TEAM_INFO_PATH,
            'api_time'  => $this->getMillisecond()
        ];
        $params = [
            'query'     => [
                'version'=> 2
            ],
            'header'    => Auth::getInstance($option)->header()
        ];
        $res = $this->handleCurl('GET',UrlEnums::FJURL.UrlEnums::LOL_TEAM_INFO_PATH.'?team_id=1&version=2',$params);
        if( $res['code'] == 200 ){
            $data = $res['data'];
        }
        return $this->writeJson(200,$data,'请求成功');
    }

    public function test()
    {
        $tables = ['siam_lolleague','siam_dotaleague'];
        $path = [UrlEnums::LOL_LEAGUE_LIST_PATH,UrlEnums::DOTA_LEAGUE_LIST_PATH];
        for ( $i=0; $i< count($path) ; $i++ ){
            $leagueUrl = UrlEnums::FJURL.$path[$i].'?version=2&offset=0&limit=1000';
            $client = new HttpClient($leagueUrl);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => $path[$i],
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $data = $response->getBody();
            $data = json_decode($data,true);
            $table = $tables[$i];
            MysqlPool::invoke(function (MysqlObject $db)use($data,$table){
                if( $data['code'] == 200 && !empty($data['data']) ){
                    foreach ( $data['data'] as $item ){
                        $league = $db->where('league_id',$item['league_id'])
                            ->whereIn('status',[0,1,3])->getOne($table,'league_id,id');
                        if( $league ){
                            $db->where('id',$league['id'])->update($table,['status'=>$item['status']]);
                        }else{
                            $item['team_ids'] = json_encode($item['team_ids']);
                            $db->insert($table,$item);

                            break;
                        }
                    }
                }
            });
        }
    }

    public function demo()
    {
        $url = 'http://live-staging.risewinter.cn/api/lol/schedule/upcoming';
        $token = '3ef904b7-b3b9-4c74-8dea-5554f0f3f3c1';
        $canshu = 'api/lol/schedule/finish';

        $nations = array("Australia","Canada","Poland","eqeq","444","5555","测试","asss");

        $stringParts = str_split($canshu);
        sort($stringParts);
        $sign = implode('', $stringParts); // abc
        $sing = strtoupper(md5($sign));
        $params = [
            'query' => [
                'token' => $token,
                'sing'  => $sing
            ]
        ];
        $data = $this->handleCurl('GET',$url,$params);
        var_dump($data);return;

    }

    public function demo1()
    {
        $contentType = 'application/json; charset=utf-8';
        $acceptApiKey = 'ddc96672af904e3';
        $acceptApiNonce = 's143wrw54xc';
        $acceptApiTime  = time();
        $api_secret = 'bf21db5dbaba486db8c6451e37eab3a';
        $uri = '/fundata-lol-free/v2/league/list';

        $acceptApiSign = md5($acceptApiNonce.'|'.$api_secret.'|'.$acceptApiTime.'|'.$uri);
        $params = [
            'header' => [
                'Content-Type'  => $contentType,
                'Accept-ApiKey' => $acceptApiKey,
                'Accept-ApiNonce' => $acceptApiNonce,
                'Accept-ApiSign'  => $acceptApiSign,
                'Accept-ApiTime	' => time(),
            ]
        ];
        $data = $this->handleCurl('GET','http://api.varena.com'.$uri,$params);
        var_dump($data);return;
    }

    public function demo2()
    {
        $url = 'http://47.91.198.97:8082/';
        $app_key = 'IbMV78U8';
        $app_secret = 'Yfz8JRNoyoxZpO63Pex0VRIoRvGmSgwY';
        $timestamp = time();
        $resource = 'event';
        $func = 'events';
        //$event_id = 11;
        //$sign = "app_key={$app_key}app_secret={$app_secret}func={$func}resource={$resource}timestamp={$timestamp}";
        $sign = "app_key={$app_key}&app_secret={$app_secret}&func={$func}&resource={$resource}&timestamp={$timestamp}";
        $sign =strtolower(md5($sign));
        $params = [
            'query' => [
                'resource' => $resource,
                'func'     => $func,
                'timestamp'=> $timestamp,
                'sign'     => $sign,
                'app_key'  => $app_key
            ]
        ];
        $data = $this->handleCurl('GET',$url,$params);
        return $this->writeJson(200,$data,'请求成功');
    }

    public function demo3()
    {
        //返回某项目下的赛事分类
        $url = 'http://api.xxe.io';
        $app_key = 'IbMV78U8';
        $app_secret = 'Yfz8JRNoyoxZpO63Pex0VRIoRvGmSgwY';
        $timestamp = time();
        $resource = 'event';
        $func = 'matches';
        $event_id = 11;
        $queries = [
            'app_key'   => $app_key,
            'app_secret'=> $app_secret,
            'timestamp' => $timestamp,
            'resource'  => $resource,
            'func'      => $func,
            'event_id'  => $event_id
        ];
        ksort($queries);
        $sign = '';
        foreach ( $queries as $k=>$v ){
            if( $v ){
                $sign .= $k."={$v}&";
            }
        }
        if( $sign ){
            $sign = substr($sign, 0, -1);
        }
        $sign = strtolower(md5($sign));
        $params = [
            'query' => array_merge($queries,['sign'=>$sign])
        ];
        $res = $this->handleCurl('GET',$url,$params);
        $code = $res['code'] ?? $res['error_code'];
        $msg  = $res['msg']  ?? $res['error_msg'];
        $data = $res['data'] ?? [];
        //return $this->writeJson(200,$res,'success');
        return $this->writeJson($code,$data,$msg);
    }

    public function demo4()
    {
        //返回某项目下比赛列表
        $url = 'http://api.xxe.io';
        $app_key = 'IbMV78U8';
        $app_secret = 'Yfz8JRNoyoxZpO63Pex0VRIoRvGmSgwY';
        $timestamp = time();
        $resource = 'game';
        $func = 'lists';
        $event_id = 11;
        $queries = [
            'app_key'   => $app_key,
            'app_secret'=> $app_secret,
            'timestamp' => $timestamp,
            'resource'  => $resource,
            'func'      => $func,
            'event_id'  => $event_id,
            'is_bet'    => 1,
        ];
        ksort($queries);
        $sign = '';
        foreach ( $queries as $k=>$v ){
            if( $v ){
                $sign .= $k."={$v}&";
            }
        }
        if( $sign ){
            $sign = substr($sign, 0, -1);
        }
        $sign = strtolower(md5($sign));
        $params = [
            'query' => array_merge($queries,['sign'=>$sign])
        ];
        $res = $this->handleCurl('GET',$url,$params);
        $code = $res['code'] ?? $res['error_code'];
        $msg  = $res['msg']  ?? $res['error_msg'];
        $data = $res['data'] ?? [];
        //return $this->writeJson(200,$res,'success');
        return $this->writeJson($code,$data,$msg);

    }

    public function demo5()
    {
        //返回某项目下比赛列表
        $url = 'http://api.xxe.io';
        $app_key = 'IbMV78U8';
        $app_secret = 'Yfz8JRNoyoxZpO63Pex0VRIoRvGmSgwY';
        $timestamp = time();
        $resource = 'game';
        $func = 'lists';
        $event_id = 11;
        $queries = [
            'app_key'   => $app_key,
            'app_secret'=> $app_secret,
            'timestamp' => $timestamp,
            'resource'  => $resource,
            'func'      => $func,
            'event_id'  => $event_id,
            'is_bet'    => 1,
        ];
        ksort($queries);
        $sign = '';
        foreach ( $queries as $k=>$v ){
            if( $v ){
                $sign .= $k."={$v}&";
            }
        }
        if( $sign ){
            $sign = substr($sign, 0, -1);
        }
        $sign = strtolower(md5($sign));
        $params = [
            'query' => array_merge($queries,['sign'=>$sign])
        ];
        $res = $this->handleCurl('GET',$url,$params);
        $code = $res['code'] ?? $res['error_code'];
        $msg  = $res['msg']  ?? $res['error_msg'];
        $data = $res['data'] ?? [];
        //return $this->writeJson(200,$res,'success');
        return $this->writeJson($code,$data,$msg);

    }

    public function demo6()
    {
        //GET http://api.xxe.io/?resource=special&func=lists&event_id=65
        //返回某项目未开始和进行中的赛事专题列表
        //返回某项目下比赛列表
        $url = 'http://api.xxe.io';
        $app_key = 'IbMV78U8';
        $app_secret = 'Yfz8JRNoyoxZpO63Pex0VRIoRvGmSgwY';
        $timestamp = time();
        $resource = 'special';
        $func = 'lists';
        $event_id = 24;
        $queries = [
            'app_key'   => $app_key,
            'app_secret'=> $app_secret,
            'timestamp' => $timestamp,
            'resource'  => $resource,
            'func'      => $func,
            'event_id'  => $event_id,
        ];
        ksort($queries);
        $sign = '';
        foreach ( $queries as $k=>$v ){
            if( $v ){
                $sign .= $k."={$v}&";
            }
        }
        if( $sign ){
            $sign = substr($sign, 0, -1);
        }
        $sign = strtolower(md5($sign));
        $params = [
            'query' => array_merge($queries,['sign'=>$sign])
        ];
        $res = $this->handleCurl('GET',$url,$params);
        $code = $res['code'] ?? $res['error_code'];
        $msg  = $res['msg']  ?? $res['error_msg'];
        $data = $res['data'] ?? [];

//        if( !empty($data) ){
//            foreach ( $data as $v ){
//                $queries1 = [
//                    'app_key'   => $app_key,
//                    'app_secret'=> $app_secret,
//                    'timestamp' => time(),
//                    'resource'  => 'special',
//                    'func'      => 'games',
//                    'id'        => $v['match_id']
//                ];
//            }
//        }

        //return $this->writeJson(200,$res,'success');
        return $this->writeJson($code,$data,$msg);
    }

    public function demo7()
    {
        //GET http://api.xxe.io/?resource=special&func=games&id=1
        $url = 'http://api.xxe.io';
        $app_key = 'IbMV78U8';
        $app_secret = 'Yfz8JRNoyoxZpO63Pex0VRIoRvGmSgwY';
        $timestamp = time();
        $resource = 'special';
        $func = 'games';
        $match_id = $this->request()->getRequestParam('id');
        $event_id = 24;
        $queries = [
            'app_key'   => $app_key,
            'app_secret'=> $app_secret,
            'timestamp' => $timestamp,
            'resource'  => $resource,
            'func'      => $func,
            'id'        => $match_id,
            'event_id'  => $event_id
        ];
        ksort($queries);
        $sign = '';
        foreach ( $queries as $k=>$v ){
            if( $v ){
                $sign .= $k."={$v}&";
            }
        }
        if( $sign ){
            $sign = substr($sign, 0, -1);
        }
        $sign = strtolower(md5($sign));
        $params = [
            'query' => array_merge($queries,['sign'=>$sign])
        ];
        $res = $this->handleCurl('GET',$url,$params);
        $code = $res['code'] ?? $res['error_code'];
        $msg  = $res['msg']  ?? $res['error_msg'];
        $data = $res['data'] ?? [];
        //return $this->writeJson(200,$res,'success');
        return $this->writeJson($code,$data,$msg);
    }

    public function demo8()
    {
        //9.1 比赛动态信息
        //GET http://api.xxe.io/?resource=dynamic&func=game&game_id=1

        $url = 'http://api.xxe.io';
        $app_key = 'IbMV78U8';
        $app_secret = 'Yfz8JRNoyoxZpO63Pex0VRIoRvGmSgwY';
        $timestamp = time();
        $resource = 'dynamic';
        $func = 'game';
        $match_id = $this->request()->getRequestParam('id');
        $event_id = 24;
        $queries = [
            'app_key'   => $app_key,
            'app_secret'=> $app_secret,
            'timestamp' => $timestamp,
            'resource'  => $resource,
            'func'      => $func,
            //'id'        => $match_id,
            'event_id'  => $event_id,
            'game_id'   => 34025
        ];
        ksort($queries);
        $sign = '';
        foreach ( $queries as $k=>$v ){
            if( $v ){
                $sign .= $k."={$v}&";
            }
        }
        if( $sign ){
            $sign = substr($sign, 0, -1);
        }
        $sign = strtolower(md5($sign));
        $params = [
            'query' => array_merge($queries,['sign'=>$sign])
        ];
        $res = $this->handleCurl('GET',$url,$params);
        $code = $res['code'] ?? $res['error_code'];
        $msg  = $res['msg']  ?? $res['error_msg'];
        $data = $res['data'] ?? [];
        //return $this->writeJson(200,$res,'success');
        return $this->writeJson($code,$data,$msg);
    }

    public function demo9()
    {
        $db = Mysql::defer('mysql');
        $team_ids = $db->getColumn('siam_dotateams','team_id');

        foreach ( $team_ids as $team_id ){
            $url = UrlEnums::FJURL.UrlEnums::DOTA_PLAYERS_PATH."?version=2&team_id={$team_id}";
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => UrlEnums::DOTA_PLAYERS_PATH,
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $content = $response->getBody();
            var_dump($content);
        }
    }

    public function test10()
    {

    }

    public function actionNotFound(?string $action)
    {
        parent::actionNotFound($action); // TODO: Change the autogenerated stub
    }
}